//rotate direction
var rotate = (d, clockwise = true) => {
    var arr = ['E', 'S', 'W', 'N']
    var idx = arr.indexOf(d);
    if (clockwise) return arr[(idx + 1) == 4 ? 0 : idx + 1];
    return arr[(idx - 1) < 0 ? arr.length - 1 : idx - 1];
}
//move forward direction by one unit
var move = ([x, y], d) => {
    var moves = {
        'N': [0, 1],
        'S': [0, -1],
        'W': [-1, 0],
        'E': [1, 0]
    }
    return [x + moves[d][0], y + moves[d][1]]
}

function execute(code) {
    code = code.replace(/(F|L|R)(\d+)/g, (_, a, b) => a.repeat(b))
    var d = 'E';
    var out = []
    var [x, y] = [0, 0]
    var routes = []
    routes.push([x, y]);
    for (c of code) {
        switch (c) {
            case 'F':
                var p = move(routes[routes.length - 1], d);
                routes.push(p)
                break;
            case 'L':
                d = rotate(d, false);
                break;
            case 'R':
                d = rotate(d);
                break;
        }
    }
    var [max_x, max_y, min_x, min_y] = [-Infinity, -Infinity, Infinity, Infinity]
    for (p of routes) {
        [max_x, max_y, min_x, min_y] = [Math.max(p[0], max_x), Math.max(p[1], max_y),
            Math.min(p[0], min_x), Math.min(p[1], min_y)
        ];
    }
    var [M, N] = [max_y - min_y + 1, max_x - min_x + 1];
    var out = []
    for (var i = 0; i < M; i++) {
        var row = []
        for (var j = 0; j < N; j++) {
            row[j] = ' ';
        }
        out.push(row);
    }
    for (p of routes) {
        var i = max_y - p[1];
        var j = p[0] - min_x;
        out[i][j] = '*'
    }
    out = out.map(v => v.join(''))
    return out.join('\r\n');
}
